<?php
/*
 * @分销商城
 * @功能说明：卖家中心
 * @更新说明：暂无更新
 * @文件名 SalerController.class.php
 * @编码 UTF-8
 * @创建时间 2016-3-8 下午12:03:10
 * @创建人 XING
 */

namespace wap\Controller;
class SalerController extends ApibaseController
{
	private $appId;
	private $appSecret;
    /*
	 * 分销商城_卖家中心首页
	 * @date: 2016-3-8 下午12:03:36
	 * @editor: XING
	 */
	public function index(){
		$levelData = M('CustEntity')->field('salelevel,cust_realname,cust_mobile,is_check,cust_img')
				   ->where(array('cust_id'=>session('loginUid')))->find();
		$this->sek = mySpreadSek(session('loginUid'));
		$this->assign('cust_img', transUrl($levelData['cust_img']));
		if($levelData['salelevel']){
			if($levelData['cust_realname'] && $levelData['cust_mobile'] && $levelData['is_check'] == '1'){
				$this->assign('level',$levelData['salelevel']);
				$this->display('saler/index');
			}else if($levelData['is_check'] == '-1'){
				$this->assign('msg','您的资料已完善！<br/>请您耐心等待审核!');
				$this->display('saler/noauth');
			}else{
				$this->display('saler/agreement');
			}
		}else{ 
			$this->assign('msg','抱歉, 您还没有卖家权限<br/>联系代理开通吧~');
			$this->display('saler/noauth');
		}
	}

	/*
	 * 分销商城_嗨呗总监升级计划
	 * @date: 2016-06-01 14:05:00
	 * @editor: WENCUN
	 * */
	public function zjPlan(){
		$this->display('/saler/plan');
	}

	/*
	 * 分销商城_店铺嗨币
	 * @date: 2016-05-25 19:05:00
	 * @editor: WENCUN
	 * */
	public function hpMoney(){
		$getData = M('CustEntity')->field(array('hp_money'))->where(array('cust_id'=>session('loginUid')))->find();
		$this->assign('getData',$getData);
		$this->display('/saler/hpmoney');
	}
	
    /*
	 * 分销商城_店铺订单
	 * @date: 2016-3-17 下午1:33:13
	 * @editor: XING
	 */
	public function bizOrder(){
		$page = I('get.page') ?: 1;$perpage = I('get.perpage') ?: 10;
		$sql = 'SELECT fx_order_collect.* FROM fx_order_collect 
				INNER JOIN fx_order_entity 
				ON fx_order_entity.order_id = fx_order_collect.order_id 
				WHERE order_status IN(1,2,3,4) AND biz_cust_id = '.session('loginUid').' ORDER BY pay_at DESC LIMIT '.($page-1)*$perpage.','.$perpage;
		$getList = CQuery($sql);
		
		$this->assign('dataout',$getList);
		$this->display('saler/bizlist');
	}
	
    /*
	 * 分销商城_消息提示页
	 * @date: 2016-3-23 下午12:16:18
	 * @editor: XING
	 */
	public function noauth(){
		$this->assign('msg',I('get.msg') ?: '系统出错，请重试~');
		$this->display('saler/noauth');
	}
	
    /*
	 * 分销商城_商家提现
	 * @date: 2016-3-17 下午4:51:07
	 * @editor: XING
	 */
	public function cashOut(){
		if(I('post.mon') && I('post.bank') && I('post.dosubmit') && I('post.enckey') == substr(md5(C("ENCKEY").session("loginUid")."cashOut"),3,8)){
			$bottlerNum = M('CustBottler')
						->where(array('is_waste'=>'0','cust_id'=>trim(session('loginUid'))))->sum('finance_money');
			if(I('post.mon') > $bottlerNum){
				jsonRespons(0, '账户余额不足');
			}
			$getBankData = M('CustBank')
						 ->where(array('bank_id'=>I('post.bank')))->find();
			if(!$getBankData){
				jsonRespons(0, '提现银行数据有误');
			}
			$cashMoney = M('CustCash');
			$cashMoney->startTrans();
			$getUseMsg = M('CustEntity')
					   ->where(array('cust_id'=>session('loginUid')))->find();
			$effectCash = $cashMoney->lock(true)->add(array(
					'cust_id' => session('loginUid'),
					'cust_realname' => $getUseMsg['cust_realname'],
					'cust_mobile' => $getUseMsg['cust_mobile'],
					'bank_name' => $getBankData['bank_name'],
					'bank_uname' => $getBankData['bank_uname'],
					'bank' => $getBankData['bank'],
					'bank_card' => $getBankData['bank_card'],
					'cash_money' => trim(I('post.mon')),
					'cash_status' => '0',
					'add_at' => time()
			));
			if($effectCash){
				$cashBottler = M('CustBottler');
				$effectBottler = $cashBottler->lock(true)->add(array(
						'cust_id' => session('loginUid'),
						'cust_cashid' => $effectCash,
						'finance_money' => -(trim(I('post.mon'))),
						'money_remark' => '账户提现支出',
						'is_waste' => '0',
						'add_at' => time()
				));
				if($effectBottler){
					$cashBottler->commit();
					$cashMoney->commit();
					//todo 提现申请模板消息推送
					curl($_SERVER['SERVER_NAME'].'/jsssdk/applyCash',array('cust_id'=>session('loginUid'),'cash_money'=>trim(I('post.mon'))));
					jsonRespons(1, '申请提现成功');
				}else{
					$cashBottler->rollback();
					$cashMoney->rollback();
					jsonRespons(0, '提现失败');
				}
			}else{
				$cashMoney->rollback();
				jsonRespons(0, '操作失败');
			}
		}else{
			jsonRespons(0, '非法请求');
		}
	}

	/*
     * 分销商城_店铺奖金明细
     * @date: 2016-05-07 13:09:00
     * @editor: WENCUN
     * */
	public function bonus(){
		$bonus = M('CustBottler')
			->field(array('money_remark','finance_money','add_at'))
			->where(array('cust_id'=>session('loginUid'),'order_id'=>'0','cust_cashid'=>'0','is_waste'=>'0'))->order(array('add_at'=>'DESC'))->select();
		$this->assign('bonus',$bonus);
		$this->display('saler/bonus');
	}

    /*
	 * 分销商城_授权书
	 * @date: 2016-3-18 下午2:09:44
	 * @editor: XING
	 */
	public function passport(){
		$url = './squan.png';
		$getLoginMsg = M('CustEntity')->field(array('cust_realname', 'promit_at', 'salelevel'))
					 ->where(array('cust_id'=>session('loginUid')))->find();
		$authArr = array('没有权限','嗨呗店长','嗨呗经理','嗨呗总监');
		$image = new \Think\Image();
		$image->open($url);
		$data = $image->text('                '.$getLoginMsg['cust_realname'],'./3.TTF',18,'#FCFCFC',5,'-63','0')
			  ->text('                       300'.date('mdY',$getLoginMsg['promit_at']).session('loginUid').date('dm',$getLoginMsg['promit_at']),'./simfang.TTF',18,'#FCFCFC',5,'-106','0')
			  ->text('                                                                    授权日期：'.date('Y-m-d',$getLoginMsg['promit_at']),'./3.TTF',18,'#FCFCFC',8,'-80','0')
			  ->text($authArr[$getLoginMsg['salelevel']],'./3.TTF',18,'#FCFCFC',5,'89','0')->save("./water1.jpg");
				
		$this->display('saler/sqs');
	}
	
    /*
	 * 分销商城_店铺升级
	 * @date: 2016-3-18 下午3:20:19
	 * @editor: XING
	 */
	public function inlevel(){
		if(I('post.dosubmit')){
			$setRecs = spotSek(trim(I('post.sek')));
			if(!I('post.sek') || !$setRecs){
				jsonRespons(0, '推广参数失效');
			}
			$level = M('CustEntity')
				   ->getFieldByCustId(session('loginUid'),'salelevel');
			$is_riz_level = 0;
			if($level == '0' && in_array(I('post.type'),array('1','2'))){
				if(I('post.type') == '1'){
					$priceNum = getSysConfig('levelhPrice');
				}else if(I('post.type') == '2'){
					$priceNum = getSysConfig('levelbPrice');
					$is_riz_level = 1;
				}
			}else if($level == '1'){
				$priceNum = getSysConfig('levelhbPrice');
				$is_riz_level = 2;
			}
			$orderId = date('YHd').rand(10,99).date('sim').rand(100,999);
			$putOrderMain = M('OrderEntity')->add(array(
					'order_id' => $orderId,
					'order_amount' => $priceNum,
					'order_pay' => $priceNum,
					'order_discount' => '0',
					'order_status' => '0',
					'remark' => $is_riz_level.'_'.$priceNum.'_'.$setRecs,
					'cust_id' => session('loginUid'),
					'nickname' => session('loginNickname'),
					'receive_name' => session('loginNickname'),
					'receive_mobile' => '',
					'receive_provice' => '',
					'receive_city' => '',
					'receive_address' => '',
					'order_type' => '1',
					'add_at' => time(),
					'update_at' => time()
			));
			if($putOrderMain){
				dataFormat($orderId,1,'success');
			}else{
				jsonRespons(0, '订单生成失败');
			}
		}
		
		$getLoginMsg = M('CustEntity')->field('salelevel,parent_id')
					 ->where(array('cust_id'=>session('loginUid')))->find();
		if(I('get.sek') && !$getLoginMsg['salelevel']){
			$checkRef = spotSek(trim(I('get.sek')));
			if($checkRef){
				if($checkRef == session('loginUid')){
					redirect('/saler/index');die();
				}
				$getSalerMsg = M('CustEntity')
							 ->where(array('cust_id'=>$checkRef))->find();
				if($getSalerMsg && $getSalerMsg['salelevel'] > 0){
					$this->assign('level',$getLoginMsg['salelevel']);
					$this->display('saler/inlevel');
				}else{
					$this->assign('msg','无效推广链接[1002]');
				}
			}else{
				$this->assign('msg','无效推广链接[1003]');
			}
			$this->display('saler/noauth');
		}elseif($getLoginMsg['salelevel'] > 0){
			$checkRef = spotSek(trim(I('get.sek')));
			if($checkRef == session('loginUid') || $getLoginMsg['salelevel'] == '3'){
				redirect('/saler/index');die();
			}
			$this->assign('level',$getLoginMsg['salelevel']);
			$this->assign('sek',mySpreadSek($getLoginMsg['parent_id']));
			$this->display('saler/inlevel');
		}else{
			$this->assign('msg','无效推广链接[1004]');
		}
		$this->display('saler/noauth');
	}

	/*
	 * $img_path 被压缩的图片的路径
	 * $thumb_w 压缩的宽
	 * $save_path 压缩后图片的存储路径
	 * $is_del 是否删除原文件，默认删除
	 */
	public function thumb_img($img_path, $thumb_w, $save_path, $is_del = true){
		$image = new \Think\Image();
		$image->open($img_path);
		$width = $image->width(); // 返回图片的宽度
		if($width > $thumb_w){
			$width = $width/$thumb_w; //取得图片的长宽比
			$height = $image->height();
			$thumb_h = ceil($height/$width);
		}

		//如果文件路径不存在则创建
		$save_path_info = pathinfo($save_path);
		if(!is_dir($save_path_info['dirname'])) mkdir ($save_path_info['dirname'], 0777);

		$image->thumb($thumb_w, $thumb_h)->save($save_path);

		if($is_del) @unlink($img_path); //删除源文件
	}
	
    /*
	 * 分销商城_卖家资料编辑
	 * @date: 2016-3-22 下午2:04:11
	 * @editor: XING
	 */
	public function edit(){
		if(I('get.ajax')){
			$url = upimgs($_FILES,'identity');
			self::thumb_img(DIRROOT.'/statics'.$url[0],1200,DIRROOT.'/statics'.$url[0],false);
			dataFormat($url[0]);
		}
		if(I('post.dosubmit')){
			$data = array(
						'cust_realname' => trim(I('post.cust_realname')),
						'cust_mobile' => trim(I('post.cust_mobile')),
						'identity' => trim(I('post.cust_identity')),
						'identity_img' => trim(I('post.identity_img')),
						'is_check' => '-1'
					);
			$putEffect = M('CustEntity')
					   ->where(array('cust_id'=>session('loginUid')))->setField($data);
			if($putEffect){
				$this->assign('msg','您的资料已完善！<br/>请您耐心等待审核!');
				$this->display('saler/noauth');
			}else{
				$this->assign('msg','操作失败');
			}
		}else{
			$this->display('saler/edit');
		}
//		else{
//			$this->assign('msg','无效参数请求');
//		}
		//$this->assign('url','/saler/index');
	}
	
    /*
	 * 分销商城_银行卡管理
	 * @date: 2016-4-2 上午11:42:53
	 * @editor: XING
	 */
	public function cardlist(){
		$card = M('CustBank')
			  ->where(array('cust_id'=>session('loginUid')))->order(array('is_default'=>'desc'))->select();
		$this->assign('cardlist',$card);
		$this->display('saler/card');
	}
	
    /*
	 * 分销商城_添加银行卡
	 * @date: 2016-4-2 下午2:28:33
	 * @editor: XING
	 */
	public function editCart(){
		if(!I('post.bank') || !I('post.bank_uname') || !I('post.bank_card')){
			jsonRespons(0, '提现信息 不完整');
		}
		if(!I('post.bank_name') && I('post.bank') != '支付宝'){
			jsonRespons(0, '支行名称必须填写');
		}
		if(I('post.id') && I('post.dosubmit')){
			$putEffect = M('CustBank')->where(array('bank_id'=>I('post.id')))->setField(array(
					'bank' => I('post.bank'),
					'bank_name' => I('post.bank_name'),
					'bank_uname' => I('post.bank_uname'),
					'bank_card' => I('post.bank_card'),
					'cust_id' => session('loginUid'),
					'update_at' => time()
			));
			if($putEffect){
				jsonRespons(1, '更新成功');
			}else{
				jsonRespons(0, '操作失败');
			}
		}elseif(I('post.dosubmit')){
			$putInsert = M('CustBank')->add(array(
						'bank' => I('post.bank'),
						'bank_name' => I('post.bank_name'),
						'bank_uname' => I('post.bank_uname'),
						'bank_card' => I('post.bank_card'),
						'cust_id' => session('loginUid'),
						'add_at' => time(),
						'update_at' => time()				
					));
			if($putInsert){
				jsonRespons(1, '添加成功');
			}else{
				jsonRespons(0, '操作失败');
			}
		}
	}
	
    /*
	 * 分销商城_设置默认银行卡
	 * @date: 2016-4-2 下午3:18:52
	 * @editor: XING
	 */
	public function setDefault(){
		if(I('get.data')){
			$dataArr = explode('_',trim(I('get.data')));
			$setDefault = M('CustBank')
						->where(array('cust_id'=>$dataArr[0]))->setField(array(
								'is_default' => '0',
								'update_at' => time()
						));
			if($setDefault){
				$putSuccess = M('CustBank')
					->where(array('cust_id'=>$dataArr[0],'bank_id'=>$dataArr[1]))->setField(array(
						'is_default' => '1',
						'update_at' => time()
					));
				if($putSuccess)
					jsonRespons(1, '设置成功');
				else
					jsonRespons(0, '操作失败');
			}else{
				jsonRespons(0, '操作失败');
			}
		}else{
			jsonRespons(0, '非法请求');
		}
	}

    /*
	 * 分销商城_删除银行卡
	 * @date: 2016-4-2 下午3:55:20
	 * @editor: XING
	 */
	public function drop(){
		if(I('get.id')){
			$setDelete = M('CustBank')
					   ->where(array('cust_id'=>session('loginUid'),'bank_id'=>I('get.id')))->delete();
			if($setDelete){
				jsonRespons(1, '删除成功');
			}else{
				jsonRespons(0, '删除失败');
			}
		}else{
			jsonRespons(0, '非法请求');
		}
	}

	
	/*
	 * 分销商城_店铺二维码分享
	 * */
	public function qCode(){
		$this->appId = 'wx1aa38ea2d042537d';
		$this->appSecret = '98da9e129edc24f8ef4b85906f7b9a8e';
		$signPackage = $this->getSignPackage();
		$this->assign('signPackage',$signPackage);
		$this->display('saler/qcode');

	}

	public function getSignPackage() {
		$jsapiTicket = $this->getJsApiTicket();
		$url = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
		$timestamp = time();
		$nonceStr = $this->createNonceStr();
		// 这里参数的顺序要按照 key 值 ASCII 码升序排序
		$string = "jsapi_ticket=$jsapiTicket&noncestr=$nonceStr&timestamp=$timestamp&url=$url";
		$signature = sha1($string);
		$signPackage = array(
		  "appId"     => $this->appId.trim(),
		  "nonceStr"  => $nonceStr,
		  "timestamp" => $timestamp,
		  "url"       => $url,
		  "signature" => $signature,
		  "rawString" => $string
		);
		return $signPackage; 
	  }



	private function createNonceStr($length = 16) {
		$chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
		$str = "";
		for ($i = 0; $i < $length; $i++) {
			$str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
		}
		return $str;
	}


	 private function getJsApiTicket() {
		 $data=$this->getAccessToken();
		 $url ='https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token='.$data.'&type=jsapi';
		 $res = json_decode($this->httpGet($url),true);
		 $ticket = $res['ticket'];
         return $ticket;
  }

   public function getAccessToken() {
		$url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$this->appId."&secret=".$this->appSecret;
		$res = json_decode($this->httpGet($url),true);
		$data=$res['access_token'];
	  return $data;
  }

	function httpGet($url)
	{
		$curl = curl_init();
		curl_setopt($curl, CURLOPT_URL, $url);
		curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
		curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
		curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
		$output = curl_exec($curl);
		curl_close($curl);
		return $output;
	}


}